<?php
class TInstances
{
	private static $entry;

	private static $plugins = array(
		'f' => array(),
		's' => array(),
		'l' => array()
	);

	private static function init(){
		if(isset(self::$entry)) return;

		$front = array();
		$last  = array();

		self::$entry = true;
		$dirs = scandir(TConf_PLUGINS_DIR);
		foreach($dirs as $dir){
			if(!is_dir(TConf_PLUGINS_DIR.DS.$dir)) continue;
			if($dir == '.' || $dir == '..') continue;
			$path  = TConf_PLUGINS_DIR.DS.$dir;
			$file  = 'setup.inc';
			$class = $dir;
			if(!is_file($path.DS.$file)) continue;
			if(class_exists($class)) continue;
			require_once($path.DS.$file);
			if(class_exists($class)){
				$i = new $class();
				if($i instanceof TPlugin_Interface){
					if($i instanceof TPlugin_Self_Interface) self::$plugins['s'][$class] = $i;
					if($i instanceof TPlugin_Front_Interface){
						if($i->pry() == 0){
							$front[$class] = $i;
						}else{
							self::$plugins['f'][$i->pry()] = $i;
						}
					}
					if($i instanceof TPlugin_Last_Interface){
						if($i->pry() == 0){
							$last[$class] = $i;
						}else{
							self::$plugins['l'][$i->pry()] = $i;
						}
					}
				}
			}
		}
		ksort(self::$plugins['f']);
		ksort(self::$plugins['l']);
		self::$plugins['f'] = array_merge($front, self::$plugins['f']);
		self::$plugins['l'] = array_merge($last,  self::$plugins['l']);
	}

	public static function getSelf(){
		self::init();
		return new ArrayObject(self::$plugins['s']);
	}

	public static function getFlont(){
		self::init();
		return new ArrayObject(self::$plugins['f']);
	}

	public static function getLast(){
		self::init();
		return new ArrayObject(self::$plugins['l']);
	}
}
